package com.demo.drools.dal.handler;

import com.alibaba.fastjson.JSON;
import com.demo.drools.rules.config.UseConfig;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author ZhouSicheng
 * @description
 * @date 2019/3/15 16:25
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class UseConfigHandler extends BaseTypeHandler<UseConfig> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, UseConfig parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public UseConfig getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return convertToEntityAttribute(s);
    }

    @Override
    public UseConfig getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return convertToEntityAttribute(s);
    }

    @Override
    public UseConfig getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return convertToEntityAttribute(s);
    }

    private UseConfig convertToEntityAttribute(String s) {
        return JSON.parseObject(s, UseConfig.class);
    }
}
